package br.gerenciadorAudio.BLL;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import br.gerenciadorAudio.Model.*;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceive extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.i(Constant.categoryLog, "Alarme iniciado");
		RegraNegocio rn = new RegraNegocio(context);
		
		Calendar calendar = Calendar.getInstance();
		Date d = calendar.getTime();
		
		try 
		{
			String dataHora = Common.ConvertToTimeString(d.getHours(), d.getMinutes());
			
			List<ProfileSchedule> profileSchedulesBegin = rn.FindScheduleActiveByBeginHour(dataHora);
			List<ProfileSchedule> profileSchedulesEnd = rn.FindScheduleActiveByEndHour(dataHora);
			
			for (ProfileSchedule profileSchedule : profileSchedulesBegin) {
				
				if(profileSchedule.Active)
					if(IsToday(profileSchedule, calendar.get(Calendar.DAY_OF_WEEK)))
					{					
						Log.i(Constant.categoryLog, "Ativando perfil: " + profileSchedule.IdPerfil);
						rn.SetVolume(context,String.valueOf(profileSchedule.IdPerfil));
					}
			}
			
			for (ProfileSchedule profileSchedule : profileSchedulesEnd) {

				if(IsToday(profileSchedule, calendar.get(Calendar.DAY_OF_WEEK)))
				{
					List<Profile> profile =  rn.ListarPerfis();
					for (Profile profile2 : profile) {
						if(profile2.Default)
						{
							Log.i(Constant.categoryLog, "Ativando perfil default: " + profileSchedule.IdPerfil);
							rn.SetVolume(context,String.valueOf(profile2.Id));	
						}
					}
				}
			}
			
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			Log.e(Constant.categoryLog, e1.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(Constant.categoryLog, e.getMessage());
		}
	}
	
	public boolean IsToday(ProfileSchedule profileSchedule,int dayOfWeek)
	{
		switch (dayOfWeek) {
		case Calendar.SUNDAY:
			if(profileSchedule.Sunday)
				return true;
			break;
		case Calendar.MONDAY:
			if(profileSchedule.Monday)
				return true;
			break;
		case Calendar.THURSDAY:
			if(profileSchedule.Thursday)
				return true;
			break;
		case Calendar.WEDNESDAY:
			if(profileSchedule.Wednesday)
				return true;
			break;
		case Calendar.TUESDAY:
			if(profileSchedule.Tuesday)
				return true;
			break;
		case Calendar.FRIDAY:
			if(profileSchedule.Friday)
				return true;
			break;
		case Calendar.SATURDAY:
			if(profileSchedule.Saturday)
				return true;
			break;
		default:
			return false;
		}
		
		return false;
	}

}
